package com.bestcem.xm.member.grpc.client;

import cn.hutool.core.collection.CollUtil;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.message.ProjectMapEntity;
import com.bestcem.xm.common.core.domain.message.RespondentSeq;
import com.bestcem.xm.common.core.domain.message.SampleCopyMessage;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.label.constant.Constants;
import com.bestcem.xm.ticket.grpc.v1.services.*;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 工单 grpc client
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/10/28
 */

@Slf4j
@Component("ticketClient")
public class TicketClient {

    @GrpcClient(GrpcClientNames.DS_TICKET)
    private TicketServiceGrpc.TicketServiceBlockingStub stub;

    public ServiceResult<Void> updateTicket(Map<String, String> ticketMap) {
        UpdateTicketMemberIdRequest.Builder builder = UpdateTicketMemberIdRequest.newBuilder();
        List<TicketMemberIdMap> memberIdMaps = new ArrayList<>();
        if (CollUtil.isNotEmpty(ticketMap)) {
            // 组装数据
            ticketMap.forEach((ticketId, memberId) -> {
                TicketMemberIdMap.Builder mapBuilder = TicketMemberIdMap.newBuilder();
                // 联系人id
                mapBuilder.setMemberId(memberId);
                // 工单id
                mapBuilder.setTicketId(ticketId);
                memberIdMaps.add(mapBuilder.build());
            });
            builder.addAllIdMaps(memberIdMaps);
            UpdateTicketMemberIdResponse response = null;
            try {
                response = stub.updateTicketMemberId(builder.build());
                if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                    log.error("【Member】更新工单联系人id失败, response: {}", response);
                    return ServiceResult.fail("更新工单失败");
                }
            } catch (StatusRuntimeException e) {
                String msg = String.format("【Member】更新工单联系人id error, %s", builder.toString());
                log.error(msg, e);
//            if (GRpcUtil.shouldRetry(e.getStatus().getCode())) {
//                return ServiceResult.<List<GroupNodeDTO>>fail(msg).setErrorCode(ErrorCodes.B0002);
//            }
                return ServiceResult.fail(msg);
            }
        }
        return ServiceResult.success();
    }

    public ServiceResult<Map<String, String>> copySample(SampleCopyMessage msg) {
        SampleCopyMessageRequest.Builder builder = SampleCopyMessageRequest.newBuilder();
        if (msg != null) {
            if (msg.getIsSample() != null) builder.setIsSample(msg.getIsSample());
            if (msg.getOrgDstId() != null) builder.setOrgDstId(msg.getOrgDstId());
            if (msg.getOrgSrcId() != null) builder.setOrgSrcId(msg.getOrgSrcId());
            if (!CollectionUtils.isEmpty(msg.getProjectList())) {
                List<com.bestcem.xm.ticket.grpc.v1.services.ProjectMapEntity> projectList = new ArrayList<>();
                for (ProjectMapEntity project : msg.getProjectList()) {
                    com.bestcem.xm.ticket.grpc.v1.services.ProjectMapEntity.Builder projectMapBuilder = com.bestcem.xm.ticket.grpc.v1.services.ProjectMapEntity.newBuilder();
                    projectMapBuilder.setDstProjectId(project.getDstProjectId());
                    projectMapBuilder.setSrcProjectId(project.getSrcProjectId());
                    projectList.add(projectMapBuilder.build());
                }
                builder.addAllProjectMaps(projectList);
            }
            if (!CollectionUtils.isEmpty(msg.getSeqList())) {
                List<com.bestcem.xm.ticket.grpc.v1.services.RespondentSeq> respondentSeqs = new ArrayList<>();
                for (RespondentSeq seq : msg.getSeqList()) {
                    com.bestcem.xm.ticket.grpc.v1.services.RespondentSeq.Builder seqBuilder = com.bestcem.xm.ticket.grpc.v1.services.RespondentSeq.newBuilder();
                    seqBuilder.setDstProjectId(seq.getDstProjectId());
                    seqBuilder.setSrcProjectId(seq.getSrcProjectId());
                    seqBuilder.setDstSeq(seq.getDstSeq());
                    seqBuilder.setSrcSeq(seq.getSrcSeq());
                    respondentSeqs.add(seqBuilder.build());
                }
                builder.addAllSeqMap(respondentSeqs);
            }
            SampleCopyMessageResponse response = null;
            try {
                response = stub.copySample(builder.build());
                if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
                    log.error("【Member】获取行业sample失败, response: {}", response);
                    return ServiceResult.fail("获取行业sample失败");
                }
                return ServiceResult.success(response.getTicketIdMap());
            } catch (StatusRuntimeException e) {
                String errMsg = String.format("【Member】获取行业sample error, %s", builder);
                log.error(errMsg, e);
                return ServiceResult.fail(errMsg);
            }
        }
        return ServiceResult.success();
    }
}
